<template>
  <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" :hide-required-asterisk="true">
    <el-form-item label="旧密码" prop="oldPassword">
      <el-input type="password" v-model="ruleForm.oldPassword" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="新密码" prop="newPassword">
      <el-input type="password" v-model="ruleForm.newPassword" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="确认密码" prop="checkPassword">
      <el-input type="password" v-model="ruleForm.checkPassword" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click.prevent="submitForm()">提交</el-button>
      <el-button @click="resetForm()">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { updatePwd } from '@/api/user'
export default {
  data(){
    const newPwd=(rule,value,callback)=>{
      if(value=== this.ruleForm.oldPassword){
        callback(new Error('新密码不能与旧密码相同'))
      }else{
        callback()
      }
    }
    const checkPwd=(rule,value,callback)=>{
      if(value!== this.ruleForm.newPassword){
        callback(new Error('两次输入的密码不一致'))
      }else{
        callback()
      }
    }
    return{
      ruleForm:{
        oldPassword:'',
        newPassword:'',
        checkPassword:''
      },
      rules:{
        oldPassword:[
          {required:true,message:'密码不能为空',trigger:'blur'},
          {pattern:/^\S{6,20}$/,message:'密码长度为6-20个字符',trigger:'blur'}
        ],
        newPassword:[
          {required:true,message:'密码不能为空',trigger:'blur'},
          {pattern:/^\S{6,20}$/,message:'密码长度为6-20个字符',trigger:'blur'},
          {validator:newPwd,trigger:'blur'}
        ],
        checkPassword:[
          {required:true,message:'密码不能为空',trigger:'blur'},
          {pattern:/^\S{6,20}$/,message:'密码长度为6-20个字符',trigger:'blur'},
          {validator:checkPwd,trigger:'blur'}
        ]
      }
    }
  },
  methods: {
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const obj={oldPwd:this.ruleForm.oldPassword,newPwd:this.ruleForm.newPassword}
          updatePwd(obj).then(res=>{
            if(res.data.status===0){
              alert('修改成功！')
              this.$refs.ruleForm.resetFields();
            }else{
              alert('旧密码错误！')
              this.$refs.ruleForm.resetFields();
            }
          })
        } else {
          console.log('校验失败！');
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.ruleForm.resetFields();
    }
  }
}
</script>

<style scoped>
.el-form{
  margin-top: 8px;
  margin-left: 5px;
  width: 500px;
}
.el-form-item:last-child{
  margin-left: 90px;
}
</style>